﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Net;

namespace Scrat.Teacher.Pages
{
    public partial class MainPage : UIPage
    {
        private MainForm _parent;
        private List<string> _onlineStudents = new List<string>();

        public MainPage(MainForm parent)
        {
            InitializeComponent();
            _parent = parent;  
        }

        private void MainPage_Shown(object sender, EventArgs e)
        {
            lbOnlineStuInfo.Items.Clear();
            _parent.StudentOnlineEvent += OnStudentOnline;
            _parent.StudentDownlineEvent += OnStudentDownline;
        }

        private void OnStudentDownline(string[] studentInfo)
        {
            string endPoint = studentInfo[0] + ":" + studentInfo[1];
            int targetIndex = _onlineStudents.FindIndex((item) => item == endPoint);

            if (targetIndex != -1)
            {
                _onlineStudents.RemoveAt(targetIndex);

                Invoke(new Action(() =>
                {
                    lbOnlineStuInfo.Items.RemoveAt(targetIndex);
                }));
            }
        }

        private void OnStudentOnline(string[] studentInfo)
        {
            string endPoint = studentInfo[0] + ":" + studentInfo[1];

            // 不存在则添加
            if (!_onlineStudents.Contains(endPoint))
            {
                // xx.xx.xx.xx:xx
                _onlineStudents.Add(endPoint);

                string strResult = "学生 [" + endPoint + "] -- 上线时间:" + studentInfo[2];

                Invoke(new Action(() => 
                {
                    lbOnlineStuInfo.Items.Add(strResult);
                    lbOnlineStuInfo.TopIndex = lbOnlineStuInfo.Count - 1;
                }));
            }            
        }

        public delegate void StudentDoubleClickDelegate(IPAddress stuIPAddr, int port);
        public event StudentDoubleClickDelegate StudentDoubleClickEvent;
        private void lbOnlineStuInfo_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int index = this.lbOnlineStuInfo.IndexFromPoint(e.Location);
            if (index != -1)
            {
                string stuInfo = _onlineStudents[index];

                IPAddress addr = IPAddress.Parse(stuInfo.Substring(0, stuInfo.IndexOf(":")));
                int port = int.Parse(stuInfo.Substring(stuInfo.IndexOf(":") + 1));

                StudentDoubleClickEvent?.Invoke(addr, port);
            }

        }
    }
}
